package org.example.mppg.handler;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Slf4j
public class JsonbTypeHandler extends BaseTypeHandler<JSONObject> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
        PGobject pgObj = new PGobject();
        pgObj.setType("jsonb");
        pgObj.setValue(parameter.toString());
        log.info("保存-----打印日志------");
        ps.setObject(i, pgObj);
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        PGobject pgObj = (PGobject) rs.getObject(columnName);
        if (pgObj != null) {
            return JSONUtil.parseObj(pgObj.getValue());
        }
        return null;
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        PGobject pgObj = (PGobject) rs.getObject(columnIndex);
        if (pgObj != null) {
            return JSONUtil.parseObj(pgObj.getValue());
        }
        return null;
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        PGobject pgObj = (PGobject) cs.getObject(columnIndex);
        if (pgObj != null) {
            return JSONUtil.parseObj(pgObj.getValue());
        }
        return null;
    }
}
